package bicing;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.appengine.repackaged.com.google.common.base.Charsets;
import common.AbstractFetcher;

public class Fetcher extends AbstractFetcher{
	
	public final static Charset charset = Charsets.ISO_8859_1;
	private final static String BICING_URL_STRING = "http://www.bicing.com/localizaciones/localizaciones.php";
	private final static String PREFIX = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><kml xmlns=\"http://www.opengis.net/kml/2.2\">";
	private final static String SUFFIX = "</kml>";
	private final Pattern kmlPattern;
	
	public Fetcher() throws MalformedURLException{
		super(BICING_URL_STRING, charset);
		kmlPattern = Pattern.compile("<Document>(.*)</Document>", Pattern.DOTALL);
	}
	
	public byte[] getKml() throws IOException{
		CharSequence html = getCharacters();
		return getKml(html);
	}
	
	public byte[] getKml(CharSequence charSequence){
		Matcher m = kmlPattern.matcher(charSequence);
		if(!m.find()){
			throw new IllegalStateException("KML not found!");
		}
		return (PREFIX + m.group(0) + SUFFIX).getBytes(charset);
	}
	
}
